﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;

namespace User
{
    public static class EncryptManager
    {
        static readonly Encoding encoding = Encoding.UTF8;
        /// <summary>
        /// 读取账户数据并解密成对象字典
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, Account> ReadUserData()
        {
            var base64_data = Convert.FromBase64String(Properties.Settings.Default.data);
            var key = Security.EncryptSHA256(encoding.GetBytes(Properties.Settings.Default.aes_key));
            var iv = Security.EncryptMD5(encoding.GetBytes(Properties.Settings.Default.aes_iv));
            var raw_data = Security.DecryptStringFromBytes_Aes(base64_data, key, iv, encoding);
            return JsonConvert.DeserializeObject<Dictionary<string, Account>>(raw_data);
        }
        /// <summary>
        /// 加密账户数据并保存
        /// </summary>
        /// <param name="data"></param>
        public static void SaveUserData(Dictionary<string, Account> data)
        {
            var raw_data = JsonConvert.SerializeObject(data);
            var key = Security.EncryptSHA256(encoding.GetBytes(Properties.Settings.Default.aes_key));
            var iv = Security.EncryptMD5(encoding.GetBytes(Properties.Settings.Default.aes_iv));
            var base64_data = Convert.ToBase64String(Security.EncryptStringToBytes_Aes(raw_data, key, iv));
            Properties.Settings.Default.data = base64_data;
            Properties.Settings.Default.Save();
        }


        /// <summary>
        /// 更改指定用户密码
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        public static void ChangePassword(Account account, string password)
        {
            account.password = Security.EncryptHMAC512(password, account.key, encoding);
        }
        /// <summary>
        /// 验证指定用户密码
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool VertityPassword(Account account, string password)
        {
            return Security.VertifyHMAC512(password, account.password, account.key, encoding);
        }

        /// <summary>
        /// 将json文本加密 覆盖 旧账户数据
        /// </summary>
        /// <param name="json"></param>
        public static void JsonConvert2Config(string json)
        {
            var data = JsonConvert.DeserializeObject<Dictionary<string, Account>>(json);
            SaveUserData(data);
        }
    }
}
